package com.minivision.sdktestdemo.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.controler.ui.activity.MusicMiniPlayControler;
import com.minivision.sdktestdemo.controler.ui.activity.MusicPlayControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.model.MusicProvider;
import com.minivision.sdktestdemo.model.Provider;
import com.minivision.sdktestdemo.service.MusicService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MusicPlayActivity extends AppCompatActivity implements
        MusicPicFragment.OnFragmentInteractionListener, MusicControlHandler.onProgressUpdated,
        MusicPlayControler.OnChangeOrder, MusicMiniPlayControler.PlayListGetter{
    private MusicService mService;
    private MusicPlayControler mControler;
    private LrcListener mLrcListener;
    private Fragment mNowFragment;
    private LinkedList<Fragment> mFragments;

    @Bind(R.id.content_layout)
    FrameLayout mContentLayout;

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((MusicService.LocalBinder) service).getService();
            mService.setHandler(new MusicControlHandler(MusicPlayActivity.this));
            //初始化控件的状态
            PlayMusicEvent event = mService.getPlayingMusic();
//            mControler.init(event);
            mControler.updateMusicStatus(event);
            //如果正在播放则开始更新进度
            if (event != null && event.mStatus == PlayMusicEvent.PLAY) {
                mService.startUpdate();
            }
            //更新显示的图片
            OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) getSupportFragmentManager().getFragments().get(0);
            listener.update(event);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    @Bind(R.id.tool_bar)
    MarqueeToolbar mToolBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_music_play);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    interface LrcListener {
        void onLrcChanged(long time);
        void onMusicChanged(String name);
    }

    public void switchFragment(Fragment to) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.hide(mNowFragment);
        if (!to.isAdded()) {
            fragmentTransaction.add(R.id.content_layout, to, null);
        } else {
            fragmentTransaction.show(to);
        }
        fragmentTransaction.commit();
        mFragments.add(mNowFragment);
        mNowFragment = to;
    }

    private void initData() {
        mControler = new MusicPlayControler(this);
        mFragments = new LinkedList<>();
    }

    private void initView() {
        //设置切换动画
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        //初始化toolbar的样式
        initToolBar();
        //加载显示专辑封面的fragment
        initFragment();
        mControler.init();
    }

    public void initToolBar() {
        setSupportActionBar(mToolBar);
        mToolBar.setLogo(null);
        mToolBar.selectTitle();
        mToolBar.setNavigationIcon(R.drawable.ic_action_arrow_left);
        mToolBar.inflateMenu(R.menu.detail_top_menu);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicPlayActivity.this.onBackPressed();
            }
        });
    }

    private void initFragment() {
        MusicPicFragment musicPicFragment = MusicPicFragment.newInstance("", "");
        mNowFragment = musicPicFragment;
        mFragments.add(mNowFragment);
//        switchFragment(musicPicFragment);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.content_layout, musicPicFragment);
        transaction.commit();
    }

    @Override
    protected void onStart() {
        bindService(new Intent(this, MusicService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.detail_top_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onStop() {
        unbindService(mServiceConnection);
        EventBus.getDefault().unregister(this);
        mControler.stopThreadPool();
        super.onStop();
    }

    @Override
    public void update(int value, int max) {
        //实时更新进度
        if (mControler != null) {
            if (mNowFragment instanceof MusicLrcFragment) {
                mLrcListener.onLrcChanged(value);
            }
            mControler.update(value, max);
        }
    }

    @Override
    public void startUpdate() {
        if (mService != null) {
            mService.startUpdate();
        }
    }

    @Override
    public void stopUpdate() {
        if (mService != null) {
            mService.stopUpdate();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateMusic(PlayMusicEvent event) {
        //更新标题和其他状态
        mControler.updateMusicStatus(event);
        //更新显示的图片
        OnFragmentUpdatedListener listener = (OnFragmentUpdatedListener) getSupportFragmentManager().getFragments().get(0);
        listener.update(event);
        if (mNowFragment instanceof MusicLrcFragment) {
            mLrcListener.onMusicChanged(event.mName);
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void updateMusic(DataModificationEvent event) {
        switch (event.mAction) {
            case DataModificationEvent.ACTION_LIST_CLEAR:
                Provider.setAllChanged(MusicProvider.getInstance(MusicPlayActivity.this));
                MusicPlayActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MusicPlayActivity.this.mService.getPlayingMusic().mUri = "";
                        MusicPlayActivity.this.finish();
                    }
                });
                break;
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public PlayMusicEvent getPlayingMusic() {
        if (mService != null) {
            return mService.getPlayingMusic();
        }
        return null;
    }

    @Override
    public void changeFragment() {
        if (mFragments.size() == 1) {
            mFragments.add(MusicLrcFragment.newInstance("",""));
            mLrcListener = (LrcListener) mFragments.getLast();
        }
        int index = mFragments.indexOf(mNowFragment);
        index = (index + 1)%2;
        switchFragment(mFragments.get(index));
        if (index == 1) {
            mLrcListener.onMusicChanged(mService.getPlayingMusic().mName);
        }
    }

    @Override
    public void changeOrder() {
        if (mService != null) {
            mService.changeOrder();
        }
    }

    @Override
    public List<MusicBean> getPlayList() {
        if (mService != null) {
            return mService.getPlayList();
        }
        return null;
    }
}

